<template>
<div>
  <div class="layout">
    <div class="register-container">
      <Subtitle :text="$t('register.title')" />
      <div class="create-text">
        <div class="title">{{ $t('register.createAccount') }}</div>
        <i18n path="register.createDescription" class="desc">
          <a place="createLink" @click="handleGohome">{{ $t('register.createLink') }}</a>
        </i18n>
      </div>
      <div class="form">
        <div class="input-group">
          <IntelInput
              :label="$t('register.inputEmail')"
              v-model="email"
              :placeholder="$t('register.inputEmail')"
              class="register-input"
              @blur="handleEmailInputBlur"
              :error="!emailValid"
          />
          <div class="divider-space"></div>
          <IntelInput
              :label="$t('register.captcha')"
              v-model="captcha"
              type="captcha"
              :placeholder="$t('register.captcha')"
              class="register-input"
              @request="handleRequestCaptcha"
              :error="!captchaValid"

          />
        </div>
        <IntelInput
            :label="$t('register.emailCode')"
            v-model="emailCode"
            type="validCode"
            :placeholder="$t('register.emailCode')"
            :getCodeText="getCodeText"
            class="register-input"
            @getCode="handleEmailCodeClick"
        />
        <IntelInput
            :label="$t('register.inputPassword')"
            v-model="password"
            type="password"
            :placeholder="$t('register.inputPassword')"
            class="register-input"
            :error="!passwordValid && verifyValid"
            @blur="handlePasswordInputBlur"
            @input="handlePasswordInputChange"
        />
        <div class="password-prompt">
          <div :class="[{ 'text-blue': wordValid },  'text']">必须包含一个字母</div>
          <div :class="[{ 'text-blue': numberValid },  'text']">必须包含一个数字</div>
          <div :class="[{ 'text-blue': characterValid },  'text']">必须包含一个特殊字符</div>
          <div :class="[{ 'text-blue': lengthValid },  'text']">长度必须为 8 至 15 个字符</div>
<!--          <div :class="[{ 'text-green': repeatValid },  'text']">不能连续重复两次以上相同的字符</div>-->
        </div>
        <IntelInput
            :label="$t('register.inputPasswordVerify')"
            type="password"
            v-model="passwordVerify"
            :placeholder="$t('register.inputPasswordVerify')"
            class="register-input"
            :error="!verifyValid"
            @blur="handleVerifyInputBlur"
            @input="handleVerifyInputChange"
        />
        <div class="password-prompt" v-if="!verifyValid">
          <div style="color: red">两次密码不一致</div>
        </div>
        <div class="submit-button" @click="handleSubmit">{{ $t('register.createButton') }}</div>
      </div>
    </div>
  </div>
  <Alert v-if="alertShow" @ok="() => alertShow = false" :content="alertContent"/>
</div>
</template>

<script>
import IntelInput from "../../components/common/IntelInput";
import Subtitle from "../../components/common/Subtitle";
import {getEmailCode, getUserInfo, register, validEmail} from "../../api/service";
import Alert from "../../components/common/Alert";

export default {
  name: "faq",
  components: {
    IntelInput,
    Subtitle,
    Alert
  },
  data () {
    return {
      email: '',
      password: '',
      passwordVerify: '',
      alertShow: false,
      alertContent:  '',
      emailValid: true,
      passwordValid: true,
      verifyValid: true,
      wordValid: false,
      numberValid: false,
      characterValid: false,
      lengthValid: false,
      captcha: '',
      captchaValid: true,
      emailCode: '',
      ableGetCode: true,
      requestCaptchaCode: '',
      getCodeText: this.$t('valid.getEmailCode')

    }
  },
  methods: {
    handleEmailInputBlur () {
      // const reg = /^([a-zA-Z0-9_-_.])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      const reg = /^\s*\w+(?:\.{0,1}[\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+\s*$/
      if (reg.test(this.email)) {
        this.validEmail()
        this.emailValid = true
      } else {
        this.emailValid = false
        this.alertShow = true
        this.alertContent = this.$t('alert.emailError')
      }
    },
    validEmail () {
      validEmail({ email: this.email }).then(res => {
        console.log(res)
        if (res.data) {
          // 邮箱不存在
          this.emailValid = false
          this.alertShow = true
          this.alertContent = this.$t('alert.notInvite')
        } else if(res.code === 500) {
          // 邮箱已注册
          this.emailValid = false
          this.alertShow = true
          const msg = res.message.split('$$')
          if (this.$i18n.locale === 'zh') {
            this.alertContent = msg[0]
          } else {
            this.alertContent = msg[1]
          }
        } else {
          //邮箱存在库，可以注册
          this.emailValid = true
        }
      })
    },
    handlePasswordInputChange () {
      const psw = this.password
      // 必须包含一个字母
      this.wordValid = new RegExp('^(?=.*?[A-Z])|(?=.*?[a-z])').test(psw)
      // 必须包含一个数字
      this.numberValid = new RegExp('^(?=.*?[0-9])').test(psw)
      // 必须包含一个特殊字符
      this.characterValid = new RegExp('^(?=.*?[_#?!@$%^&*-.])').test(psw)
      // 长度必须为 8 至 15 个字符
      this.lengthValid = new RegExp('^\\S{8,15}$').test(psw)

    },
    handlePasswordInputBlur () {
      // const reg = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-.]).{8,}$/
      this.passwordValid = this.wordValid && this.numberValid && this.characterValid && this.lengthValid
    },
    handleVerifyInputBlur () {
      if (this.passwordVerify) {
        this.verifyValid = this.password === this.passwordVerify
      } else {
        this.verifyValid = true
      }
    },
    handleVerifyInputChange () {
      if (this.passwordVerify) {
        this.verifyValid = this.password === this.passwordVerify
      } else {
        this.verifyValid = true
      }
    },
    handleSubmit () {
      if (this.emailValid && this.passwordValid && this.verifyValid && this.email && this.emailCode && this.captcha) {
        this.createAccount()
      } else {
        this.alertShow = true
        this.alertContent = this.$t('valid.checkInput')
      }
    },
    createAccount () {
      const that = this
      register({
        registerEmail: this.email,
        registerPasswd: this.password,
        emailVerifyCode: this.emailCode
      }).then(res => {
        console.log(res)
        if (res.code === 200) {
          // 获取用户信息
          const token = res.data
          localStorage.setItem('token', token)
          that.getUserInfo()
        } else {
          //注册失败
          this.alertShow = true
          const msg = res.message.split('$$')
          if (this.$i18n.locale === 'zh') {
            this.alertContent = msg[0]
          } else {
            this.alertContent = msg[1]
          }
        }
      })
    },
    handleGohome () {
      this.$router.push({
        path: this.$i18n.path('')
      })
      this.$store.commit('SET_LOGIN_SHOW', true)
    },
    getUserInfo () {
      getUserInfo().then(res => {
        // 页面跳转
        console.log(res)
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        this.$router.push({
          path: this.$i18n.path('registerConfirm')
        })
      })
    },
    handleRequestCaptcha (code) {
      this.requestCaptchaCode = code
    },
    handleEmailCodeClick () {
      if (this.ableGetCode) {
        if (this.email && !this.emailValid) {
          // 邮箱不为空 并且验证通过
          this.alertShow = true
          this.alertContent = this.$t('valid.checkEmail')
        } else if (!this.captcha) {
          // 图形验证码不为空
          this.alertShow = true
          this.alertContent = this.$t('valid.checkCode')
        } else {
          // 请求邮箱验证码
          this.getEmailCode()
        }
      }
    },
    getEmailCode () {
      this.ableGetCode = false
      this.getCodeText = this.$t('valid.wait')
      const params = {
        "email": this.email,
        "imgVerifyCode": this.captcha,
        "imgVerifyCodeRequestId": this.requestCaptchaCode
      }
      getEmailCode(params).then(res => {
        console.log(res)
        this.ableGetCode = true
        if (res.code === 500) {
          this.getCodeText = this.$t('valid.getEmailCode')
          const msg = res.message.split('$$')
          this.alertShow = true
          if (this.$i18n.locale === 'zh') {
            this.alertContent = msg[0]
          } else {
            this.alertContent = msg[1]
          }
        }
        if (res.code === 200) {
          this.beginCountdown()
        }
      })
    },
    beginCountdown () {
      this.ableGetCode = false
      let num = 60
      this.getCodeText = this.$t('valid.reGet', {num: num})
      const countdown = setInterval(()=> {
        if (num > 0) {
          num -= 1
          this.getCodeText = this.$t('valid.reGet', {num: num})
        } else {
          this.ableGetCode = true
          this.getCodeText = this.$t('valid.getEmailCode')
          num = 60
          clearInterval(countdown)
        }
      },1000)
    }
  }
}
</script>

<style scoped>
.register-container {
  width: 800px;
  padding-top: 60px;
  padding-left: 120px;
  padding-bottom: 120px;
}

.create-text {
  padding-top: 0px;
}
.create-text .title {
  font-weight: bold;
  font-size: 20px;
  color: #0068B5;
  padding-bottom: 18px;
}
.create-text .desc {
  font-size: 14px;
  color: #999999;
}

.create-text .desc a {
  color: #0068B5;
  text-decoration: none;
}

.form {
  padding-top: 24px;
}
.register-input {
  margin-top: 16px;
  width: 100%;
}

.submit-button {
  width: 146px;
  height: 36px;
  color: white;
  font-size: 14px;
  text-align: center;
  line-height: 36px;
  background: #0068B5;
  cursor: pointer;
  margin-top: 16px;
}
.password-prompt {
  font-size: 14px;
  color: #999999;
  padding-top: 10px;
}
.text-blue {
  color: #0068B5;
  text-decoration: underline;
}

.input-group {
  width: 100%;
  display: flex;
}
.divider-space {
  width: 32px;
  height: 60px;
  display: inline-block;
}
</style>
